package org.x.note.swing;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

public class MusicPlayer extends JFrame implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2854926546184222766L;

	Container contentPane;
	JTextField jTextField;
	JButton jButton1, jButton2, jButton3;
	JScrollPane jScrollPane;
	File file;
	InputStream is;
	static AudioStream audioStream = null;

	public MusicPlayer() {
		initSelf();
		initComonet();
	}

	private void initComonet() {
		// TODO Auto-generated method stub
		jTextField = new JTextField();
		jTextField.setBounds(10, 50, 300, 30);

		jButton1 = new JButton("请选择歌曲");
		jButton1.setBounds(320, 50, 120, 30);
		jButton1.addActionListener(this);

		jButton2 = new JButton("播放");
		jButton2.setBounds(100, 100, 100, 50);
		jButton2.addActionListener(this);

		jButton3 = new JButton("停止");
		jButton3.setBounds(300, 100, 100, 50);
		jButton3.addActionListener(this);

		contentPane = this.getContentPane();
		contentPane.add(jTextField);
		contentPane.add(jButton1);
		contentPane.add(jButton2);
		contentPane.add(jButton3);
	}

	private void initSelf() {
		// TODO Auto-generated method stub
		this.setTitle("音乐播放器");
		this.setBounds(400, 300, 500, 400);
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLayout(null);
	}

	public void actionPerformed(ActionEvent event) {
		// TODO Auto-generated method stub
		Object temp = event.getSource();
		if (temp == jButton1) {
			JFileChooser fileChooser = new JFileChooser("F:\\音乐\\新建文件夹");
			fileChooser.showDialog(this, "请选择歌曲");
			file = fileChooser.getSelectedFile();
			jTextField.setText(file.getName());

		}
		if (temp == jButton2) {
			playMusic();
		}
		if (temp == jButton3) {
			stop();
		}
	}

	public static void stop() {
		AudioPlayer.player.stop(audioStream);
	}

	private void playMusic() {
		// TODO Auto-generated method stub

		try {
			InputStream is = new FileInputStream(file);

			audioStream = new AudioStream(is);

		} catch (IOException e) {

		}
		AudioPlayer.player.start(audioStream);
	}

	public static void main(String[] args) {
		// JFrame.setDefaultLookAndFeelDecorated(true);
		new MusicPlayer().setVisible(true);
	}

}
